package myhashtable;

public class HashTable implements HashTableInterface{

    private int length;
    private LinkedList [] linkedLists;
    private static final String msgNotFound="Cannot find object with key:";

    public HashTable() {
        this.length = 50;
        linkedLists = new LinkedList[length];
        initList();
    }

    public HashTable(int length) {
        if (length <= 0) {
            System.out.println("invalid length HashMap");
            return;
        }
        this.length = length;
        linkedLists = new LinkedList[length];
        initList();
    }

    private void initList(){
        for (int i = 0; i < linkedLists.length; i++) {
            linkedLists[i] = new LinkedList();
        }
    }

    public void put(String key, Object obj) {
        int idx = hash(key);
        if(linkedLists[idx].getLength()==0){
            linkedLists[idx].add(key, obj);
        }else{
            linkedLists[idx].addWithSort(key,obj);
        }
    }

    public Object get(String key) {
        int idx= hash(key);
        return linkedLists[idx].getByKey(key);
    }

    public void remove(String key) {
        int idx=hash(key);
        if(!linkedLists[idx].removeByKey(key)){
            System.out.println(msgNotFound+key);
        }
    }

    public int hash(String key) {
        int sum=0;
        for (int i = 0; i < key.length(); i++) {
            sum+=key.charAt(i);
        }
        if(sum<=0){
            System.out.println("invalid key HashMap");
        }
        return sum%length;
    }

    public int getLength() {
        return length;
    }
}
